import pprint
import os
import urllib.parse
import json5
from qwen_agent.agents import Assistant
from qwen_agent.tools.base import BaseTool, register_tool

import cal

cal_ = cal.Cal()

# Step 1 (Optional): Add a custom tool named `my_image_gen`.
@register_tool('phone_button_click')
class PhoneButtonClick(BaseTool):
    # The `description` tells the agent the functionality of this tool.
    description = '点击手机按钮服务, 回返当前界面信息。'
    # The `parameters` tell the agent what input parameters the tool has.
    parameters = [{
        'name': 'id',
        'type': 'string',
        'description': '描述点击按钮的resource-id。',
        'required': True
    }]

    def call(self, params: str, **kwargs) -> str:
        # `params` are the arguments generated by the LLM agent.
        ID = json5.loads(params)['id']

        return cal_.click(ID)


# Step 2: Configure the LLM you are using.
llm_cfg = {
    # Use the model service provided by DashScope:
    'model': 'qwen-max',
    'model_server': 'dashscope',
    'api_key': os.environ.get('DASHSCOPE_API_KEY', None),
    'generate_cfg': {
        'top_p': 0.8,
        # "max_input_tokens": 4000
    }
}

# Step 3: Create an agent. Here we use the `Assistant` agent as an example, which is capable of using tools and reading files.
system_instruction = '''你是一个有用的助手。你可以操作手机上的计算器进行计算任务
在收到用户请求后，你应该：
- 逐步操作手机获取计算结果
'''

tools = ['phone_button_click',]  # `code_interpreter` is a built-in tool for executing code.

bot = Assistant(llm=llm_cfg,
                system_message=system_instruction,
                function_list=tools)

# Step 4: Run the agent as a chatbot.
messages = []  # This stores the chat history.
while True:
    # For example, enter the query "draw a dog and rotate it 90 degrees".
    query = input('user query: ')
    # Append the user query to the chat history.
    messages.append({'role': 'user', 'content': query + '\n 当前的手机状况是：' + cal_.status()
                     
                     
                     })
    response = []
    for response in bot.run(messages=messages):
        # Streaming output.
        #print('bot response:')
        #pprint.pprint(response, indent=2)
        pass
    # Append the bot responses to the chat history.
    print('bot response: ' + response[-1]['content'])
    messages.extend(response)